package com.ucode.crm.service.impl;
import java.util.Date;

import com.ucode.crm.dictionary.CrmSettingField;
import com.ucode.crm.mapper.CrmSettingMapper;
import com.ucode.crm.mode.CrmSetting;
import com.ucode.crm.service.CrmSettingService;
import com.ucode.tool.util.IdentifyUtils;

import cn.hutool.json.JSONObject;

public class CrmSettingServiceImpl implements CrmSettingService {

    private CrmSettingMapper crmSettingMapper;
    
    @Override
    public int insert(String name, String value) {
        Long id = IdentifyUtils.getDefaultSnowflakeId();
        CrmSetting setting = new CrmSetting();
        setting.setId(id);
        setting.setFieldName(name);
        String fieldValue = value;
        if(CrmSettingField.level.equals(name) ||
                CrmSettingField.source.equals(name) || 
                CrmSettingField.industry.equals(name) ){
            JSONObject json = new JSONObject();
            json.put("label", value);
            json.put("value", id);
            fieldValue = json.toString();
        }
        
        setting.setFieldValue(fieldValue);
        Date now = new Date();
        setting.setCreatedTime(now);
        setting.setUpdatedTime(now);
        return crmSettingMapper.insert(setting);
    }

    @Override
    public int update(Long id, String name, String value) {
        CrmSetting setting = crmSettingMapper.findById(id);
        if(setting != null && setting.getFieldName().equals(name)){
            String fieldValue = value;
            if(CrmSettingField.level.equals(name) ||
                    CrmSettingField.source.equals(name) || 
                    CrmSettingField.industry.equals(name) ){
                JSONObject json = new JSONObject();
                json.put("value", id);
                json.put("label", value);
                fieldValue = json.toString();
            }
            
            setting.setFieldValue(fieldValue);
            return crmSettingMapper.update(setting);
        }
        return 0;
    }

}
